﻿#region 命名空间

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;
using WinnerCMS.BLL;
using WinnerCMS.Common;
using WinnerCMS.Model;
using WinnerCMS.Model.Attribute;
using WinnerCMS.Model.Enum;

#endregion

namespace WinnerCMS.WebUI.Admin.Article
{
    /// <summary>
    ///     Admin_Article_Add 的摘要说明。
    /// </summary>
    [Access("ContenAdd,ContenEdit", IsMacthMID = true)]
    public partial class Add : WebFactory.PageBase
    {
        private byte ModelId;

        /// <summary>
        ///     自定义字段
        /// </summary>
        protected bool ExtendField;

        protected void Page_Load(object sender, EventArgs e)
        {
            InitEveryPost();

            if (!IsPostBack)
            {
                if (Request.QueryString["TempFlag"] == null && Request["ID"] == null)
                {
                    Response.Redirect(Request.RawUrl + "&TempFlag=" + Guid.NewGuid());
                }

                this.txtUpDateTime.Text = DateTime.Now.ToString(CultureInfo.InvariantCulture);
                this.lblAnnexRemark.Text = "允许上传的格式：" + ModelManage.GetInfo(this.ModelId).AdminFileTypes;

                BindDropDownList();
                FieldEnabale();

                if (Request["ID"] != null) //修改界面
                {
                    EidtUI();
                }
                else //添加界面
                {
                    AddUI();
                }
            }
        }

        private void InitEveryPost()
        {
            this.ModelId = byte.Parse(Request["ModelId"]);

            if (Request["ID"] != null) //修改界面
            {
                Title = string.Concat("修改", ModelManage.GetContentName(this.ModelId));
            }
            else //添加界面
            {
                Title = string.Concat("添加", ModelManage.GetContentName(this.ModelId));
            }

            new FieldObject(this.ModelId).LoadUI(this.T_DefinedFile, out this.ExtendField);
        }

        #region  绑定DropDownList

        /// <summary>
        ///     绑定DropDownList
        /// </summary>
        private void BindDropDownList()
        {
            new CategoryManage()
                .BindDDL(this.ddlCategory, BindOption.NoLink, "<请选择栏目>", this.ModelId)
                .BindDDL(this.lblCategoryMap, BindOption.NoLink, "<不选择>", this.ModelId);
            new SpecialManage().BindDDL(this.ddlSpecialID, BindOption.NoLink, "<请选择专题>", this.ModelId);

            ServerControl.BindDropDownList(this.ddlRank, new RoleManage().BindList(false), "RoleName", "ID",
                new ListItem {Text = "<请选择>", Value = "0"});
        }

        #endregion

        private void FieldEnabale()
        {
            this.trAuthor.Visible = FieldControl.Enabale("Author");
            this.trFrom.Visible = FieldControl.Enabale("From");
            this.trHits.Visible = FieldControl.Enabale("Hits");
            this.trKey.Visible = FieldControl.Enabale("Key");

            this.trPicUrl.Visible = FieldControl.Enabale("PicUrl");
            this.trPointNum.Visible = FieldControl.Enabale("PointNum");
            this.trRank.Visible = FieldControl.Enabale("Rank");
            this.trSpecialID.Visible = FieldControl.Enabale("SpecialID");

            this.trStars.Visible = FieldControl.Enabale("Stars");
            this.trTemplateFileName.Visible = FieldControl.Enabale("TemplateFileName");
            this.trSubtitle.Visible = FieldControl.Enabale("Subtitle");
            this.trUpDateTime.Visible = FieldControl.Enabale("UpDateTime");

            //////////////////////////////////////////

            if (FieldControl.Enabale("IncludePic") == false)
            {
                this.cbkIncludePic.Visible = false;
                this.cbkIncludePic.Checked = true;
            }


            if (FieldControl.Enabale("CssClass") == false)
            {
                this.txtCssClass.Visible = false;
                this.txtCssClass.Text = "";
            }
            if (FieldControl.Enabale("AllowComment") == false)
            {
                this.cbkAllowComment.Visible = false;
                this.cbkAllowComment.Checked = true;
            }
            this.cbkIsSlide.Visible = FieldControl.Enabale("IsSlide");


            //改变选项卡
        }

        #region 添加界面

        /// <summary>
        ///     添加界面
        /// </summary>
        private void AddUI()
        {
            if (Session["Key"] != null || Session["SelectCategoryId"] != null)
            {
                this.txtKey.Text = Session["Key"].ToString();
            }

            this.hfAnnexFlag.Value = Request.QueryString["TempFlag"];


            this.btnArticleAdd.Visible = true;
            this.btnArticleAdd.Text = string.Concat("添加", ModelManage.GetContentName(this.ModelId));

            this.btnArticleEdit.Visible = false;
        }

        #endregion

        #region 修改界面

        /// <summary>
        ///     修改界面
        /// </summary>
        private void EidtUI()
        {
            var model = new ArticleManage().GetInfo(int.Parse(Request["ID"]));

            this.ddlCategory.SelectedValue = model.CategoryId.ToString();
            this.txtTitle.Text = Server.HtmlDecode(model.ContentTitle);
            this.txtSubtitle.Text = model.Subtitle;
            this.txtAuthor.Text = model.Author;
            this.txtFrom.Text = model.ComeFrom;
            this.txtKey.Text = model.Tags;
            this.CC_Content.Text = model.Content;

            this.cbkIncludePic.Checked = model.IncludePic;
            this.cbkIsSlide.Checked = model.IsSlide;
            this.cbkAllowComment.Checked = model.AllowComment;
            this.cbkIsHeadline.Checked = model.IsHeadline;
            this.cbkIsOnTop.Checked = model.IsOnTop;
            this.cbkIsElite.Checked = model.IsElite;
            this.cbkIsChecked.Checked = model.IsChecked;
            //cbkIsDraft.Checked = model.IsDraft;

            this.txtPicUrl.Text = model.PicUrl;
            this.ddlStars.SelectedValue = model.Stars.ToString();
            this.ddlRank.SelectedValue = model.Rank.ToString();
            this.NtxtPointNum.Text = model.PointNum.ToString();
            this.NtxtHits.Text = model.Hits.ToString();


            this.txtBrief.Text = model.Brief;
            this.txtTemplateFileName.Text = model.TemplateFileName;
            this.txtSEOTitle.Text = model.SEOTitle;
            this.txtSEOKeyWord.Text = model.SEOKeyWord;
            this.txtSEODescript.Text = model.SEODescript;

            this.btnArticleAdd.Visible = false;
            this.btnArticleEdit.Visible = true;
            this.btnArticleEdit.Text = string.Concat("修改", ModelManage.GetContentName(this.ModelId));

            #region 自定义字段

            string strErr = null;
            new FieldManage().ExtendFieldData(this.ModelId, false, Request["ID"], this.T_DefinedFile, ref strErr);
            if (string.IsNullOrEmpty(strErr) == false)
                MsgBox.Message(strErr, this);

            #endregion
        }

        #endregion

        #region 添加修改

        /// <summary>
        ///     添加修改
        /// </summary>
        private void AddArticle()
        {
            var Fields = new List<string>();
            var Values = new List<object>();
            foreach (TableRow tr in this.T_DefinedFile.Rows)
            {
                var c = tr.Cells[1].Controls[0];
                if (c is TextBox)
                {
                    var tb = c as TextBox;
                    Fields.Add(tb.ID);
                    Values.Add(tb.Text.Trim());
                }
                if (c is DropDownList)
                {
                    var ddl = c as DropDownList;
                    Fields.Add(ddl.ID);
                    Values.Add(ddl.SelectedValue);
                }
                if (c is RadioButtonList)
                {
                    var rbl = c as RadioButtonList;
                    Fields.Add(rbl.ID);
                    Values.Add(rbl.SelectedValue);
                }
                if (c is CheckBox)
                {
                    var cb = c as CheckBox;
                    Fields.Add(cb.ID);
                    Values.Add(cb.Checked);
                }
            }

            var model = new WinnerCMS.Model.Article
            {
                ContentTitle = this.txtTitle.Text.Trim(),
                Subtitle = this.txtSubtitle.Text.Trim(),
                Author = this.txtAuthor.Text.Trim(),
                ComeFrom = this.txtFrom.Text.Trim(),
                Editor = UserManage.Current.UserName,
                Tags = this.txtKey.Text.Trim(),
                Content = DownPic(this.CC_Content.Text, this.cbkDownPic.Checked),
                IncludePic = this.cbkIncludePic.Checked,
                IsHeadline = this.cbkIsHeadline.Checked,
                PicUrl = this.txtPicUrl.Text.Trim(),
                CategoryId = int.Parse(this.ddlCategory.SelectedValue)
            };

            var categores = new List<string>();
            foreach (ListItem li in this.lblCategoryMap.Items)
            {
                if (li.Selected)
                {
                    categores.Add(li.Value);
                }
            }
            model.CategoryIds = string.Join(",", categores.ToArray());

            model.Stars = byte.Parse(this.ddlStars.SelectedValue);
            model.Rank = short.Parse(this.ddlRank.SelectedValue);
            model.PointNum = short.Parse(this.NtxtPointNum.Text.Trim());
            model.Hits = int.Parse(this.NtxtHits.Text.Trim());
            model.UpdateTime = DateTime.Parse(this.txtUpDateTime.Text);


            model.Brief = this.txtBrief.Text.Trim();
            model.TemplateFileName = this.txtTemplateFileName.Text.Trim();

            model.IncludePic = this.cbkIncludePic.Checked;
            model.IsSlide = this.cbkIsSlide.Checked;
            model.AllowComment = this.cbkAllowComment.Checked;
            model.IsHeadline = this.cbkIsHeadline.Checked;
            model.IsOnTop = this.cbkIsOnTop.Checked;
            model.IsElite = this.cbkIsElite.Checked;

            model.IsChecked = this.cbkIsChecked.Checked;
            model.IsDraft =  this.cbkIsDraft.Checked;


            model.SEOTitle = this.txtSEOTitle.Text;
            model.SEOKeyWord = this.txtSEOKeyWord.Text;
            model.SEODescript = this.txtSEODescript.Text;

            model.Id = Convert.ToInt32(Request["ID"]);


            var resu = PolicyInjection.Create<ArticleManage>().Save(model, this.hfAnnexFlag.Value, Fields, Values);
            if (string.IsNullOrEmpty(resu.Errors) == false)
            {
                MsgBox.Message(resu.Errors, this);
            }
            else
            {
                Response.Redirect(string.Format("../Common/SaveOK.aspx?ModelId={0}&ID={1}", this.ModelId, model.Id));
            }
        }

        #endregion

        protected void btnArticleEdit_Click(object sender, EventArgs e)
        {
            AddArticle();
        }

        protected void btnArticleAdd_Click(object sender, EventArgs e)
        {
            AddArticle();
        }

        #region 下载图片

        /// <summary>
        ///     下载图片
        /// </summary>
        /// <param name="strContent"></param>
        /// <param name="DownPic"></param>
        /// <returns></returns>
        private string DownPic(string strContent, bool DownPic)
        {
            //if (DownPic == true)
            //{
            //    //读取这个栏目的图片保存路径
            //    string strPicPath = new BLL.CategoryManage().GetInfo(int.Parse(ddlCategoryId.SelectedValue)).PicPath;
            //    if (string.IsNullOrEmpty(strPicPath) == true)
            //    {
            //        CMSConfig config = CMSConfig.Instance();
            //        strPicPath = config.UpLoadFolder;
            //    }
            //    return new WinnerCMS.BLL.GatherEngine.Utilities().DownPic(strContent, DownPic, cbkDrawWatherMark.Checked, strPicPath);
            //}
            //else
            //{
            //    return strContent;
            //}

            return strContent;
        }

        #endregion
    }
}